package com.rcloud.server.sealtalk.manager;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rcloud.server.sealtalk.constant.ErrorCode;
import com.rcloud.server.sealtalk.controller.param.SubmitStepParam;
import com.rcloud.server.sealtalk.domain.CompanyInfo;
import com.rcloud.server.sealtalk.domain.UserDocList;
import com.rcloud.server.sealtalk.domain.Users;
import com.rcloud.server.sealtalk.exception.ServiceException;
import com.rcloud.server.sealtalk.service.AttachFileService;
import com.rcloud.server.sealtalk.service.CompanyInfoService;
import com.rcloud.server.sealtalk.service.UserDocListService;
import com.rcloud.server.sealtalk.service.UsersService;
import com.rcloud.server.sealtalk.xiangyun.NetOCRCommonClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: zc
 * @date: 2021/06/16
 * @description: 商户认证资料提交处理类
 * @copyright (c) 20201, rongcloud.cn All Rights Reserved
 */
@Slf4j
@Service
public class DocListManager extends BaseManager {
    @Resource
    private NetOCRCommonClient ocrCommonClient;
    @Resource
    private UserDocListService docListService;
    @Resource
    private AttachFileService attachFileService;
    @Resource
    private UsersService usersService;

    @Resource
    private CompanyInfoService companyInfoService;

    @Resource
    private FaceAuthManager faceAuthManager;


    @Transactional(rollbackFor = Exception.class)
    public String submitFile(Integer userId, MultipartFile file, Integer dataType) throws IOException {
        //文件上传后的地址信息
        String fileName = attachFileService.uploadFile(file.getBytes(), file.getOriginalFilename());
        UserDocList docList = docListService.getOne(UserDocList.builder().userId(userId).dataType(dataType).build());
        UserDocList paramsDoc = UserDocList.builder().build();
        //没有就进行添加
        if (docList == null) {
            paramsDoc.setUserId(userId);
            paramsDoc.setAuthStatus(0);
            paramsDoc.setCreateTime(new Date());
            paramsDoc.setDataType(dataType);
            paramsDoc.setPostUrl(fileName);
            docListService.saveSelective(paramsDoc);
        } else {
            //执行更新的操作
            docList.setPostUrl(fileName);
            docList.setAuthStatus(0);
            docListService.updateByPrimaryKeySelective(docList);
            if (dataType == 3) {
                //进入证件审核的接口
                try {
                    faceAuthManager.authCert(userId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return fileName;
    }

    /**
     * 商户实名认证的提交
     */

    public Boolean submitDataAuth(SubmitStepParam param, Integer userId) throws ServiceException, IOException {
        //进行实名认证增强版本的实名认证
        String result = ocrCommonClient.realNameStrengthen(param.getName(), param.getIdCardNum());
        //解析结果 并进行处理
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONObject message = jsonObject.getJSONObject("message");
        if (message.getIntValue("status") != 0) {
            throw new ServiceException(ErrorCode.IDENTIFY_AUTH_ERROR);
        }
        JSONArray policeCheckInfo = jsonObject.getJSONArray("policeCheckInfo");
        for (int i = 0; i < policeCheckInfo.size(); i++) {
            JSONObject police = policeCheckInfo.getJSONObject(i);
            JSONArray veritem = police.getJSONArray("veritem");
            for (int j = 0; j < veritem.size(); j++) {
                JSONObject item = veritem.getJSONObject(j);
                //判读认证状态字段
                if ("verify_result_status".equals(item.getString("desc"))) {
                    //获取认证状态 3代表认证成功
                    if ("3".equals(item.getString("content"))) {
                        //修改用户的认证状态，以及docList上的认证信息
                        Users paramUser = new Users();
                        paramUser.setId(userId);
                        paramUser.setIsReal(1);
                        paramUser.setName(param.getName());
                        paramUser.setIdentitycard(param.getIdCardNum());
                        paramUser.setValidDate(param.getValidDate());
                        usersService.updateByPrimaryKeySelective(paramUser);
                        //修改 身份证文件存储上的认证信息
                        List<UserDocList> userDocLists = docListService.queryCardList(userId);
                        for (UserDocList doc : userDocLists) {
                            doc.setAuthStatus(1);
                            doc.setAuthTime(new Date());
                            docListService.updateByPrimaryKeySelective(doc);
                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public Map<String, Object> queryAuthStatus(Integer userId) throws ServiceException {
        Map<String, Object> map = new HashMap<>();
        Users users = usersService.getByPrimaryKey(userId);
        List<UserDocList> userDocLists = docListService.get(UserDocList.builder().userId(userId).build());
        if (userDocLists.size() > 0) {
            Users user = usersService.getByPrimaryKey(userId);
            if (user != null && user.getIsReal() == 1) {
                map.put("authStep", "1");
            } else {
                map.put("authStep", "0");
            }
            UserDocList businessLicense = docListService.getOne(UserDocList.builder().userId(userId).dataType(3).build());
            if (businessLicense != null) {
                map.put("businessLicenseStatus", businessLicense.getAuthStatus());
            } else {
                map.put("businessLicenseStatus", "-1");
            }
            UserDocList tobaccoLicense = docListService.getOne(UserDocList.builder().userId(userId).dataType(4).build());
            if (tobaccoLicense != null) {
                map.put("tobaccoLicenseStatus", tobaccoLicense.getAuthStatus());
            } else {
                map.put("tobaccoLicenseStatus", "-1");
            }
            //有一个是 0 的 待审核 有个是2的有审核失败的 全是 1的通过   || "0".equals(map.get("tobaccoLicenseStatus").toString())
            if ("0".equals(map.get("businessLicenseStatus").toString())) {
                map.put("successTips", "认证资料已提交，正在审核中，请耐心等待！");
            }
            // || "2".equals(map.get("tobaccoLicenseStatus").toString()) || "-1".equals(map.get("tobaccoLicenseStatus").toString())
            if ("2".equals(map.get("businessLicenseStatus").toString())) {
                map.put("successTips", "您的部分资料跟法人信息不一致或证件无效，请按如下提示更新相关资料，重新认证。");
            }
        } else {
            //未提交资料
            map.put("authStep", "0");
        }
        if (users != null) {
            map.put("payAuthStatus", users.getPayAuthStatus());
            map.put("isFace", users.getIsFace());
            map.put("isMerchant", users.getIsMerchant());
            if (users.getIsMerchant() == 1) {
                //计算天数
                long day = DateUtil.betweenDay(new Date(), users.getAuthValidDate(), false);
                map.put("successTips", "恭喜您，您的资料审核成功，商户认证有效期为365天，剩余" + day + "天！");
            }
        } else {
            throw new ServiceException(ErrorCode.USER_NOT_EXIST);
        }
        return map;
    }

    /**
     * 查看用户认证内容
     */
    public Map<String, Object> queryAuthContent(Integer userId) throws ServiceException {
        Map<String, Object> map = new HashMap<>();
        Users users = usersService.getByPrimaryKey(userId);
        if (users.getIsMerchant() == 1) {
            //查询企业信息
            CompanyInfo one = companyInfoService.getOne(CompanyInfo.builder().userId(userId).build());
            if (one != null) {
                map.put("unifySocialCode",one.getUnifySocialCode());
                map.put("companyName",one.getCompanyName());
                map.put("businessScope",one.getBusinessScope());
                UserDocList tobaccoLicense = docListService.getOne(UserDocList.builder().userId(userId).dataType(4).authStatus(1).build());
                if (tobaccoLicense != null) {
                    map.put("isTobaccoLicense","1");
                }else {
                    map.put("isTobaccoLicense","0");
                }
                UserDocList foodLicense = docListService.getOne(UserDocList.builder().userId(userId).dataType(5).authStatus(1).build());
                if (foodLicense != null) {
                    map.put("isFoodLicense","1");
                }else {
                    map.put("isFoodLicense","0");
                }
            }else {
                throw new ServiceException(ErrorCode.QUERY_COMPANY_INFO_ERROR);
            }
        }else {
            throw new ServiceException(ErrorCode.USER_IS_NOT_AUTH_MERCHANT_ERROR);
        }
        return map;
    }
}